import { Model } from './model.js';
var model = new Model();
var area = require('../../utils/area.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:0,
    areaList: area.default,
    currency: '',
    province: '',
    city: '',
    area: '',
    area_address:'',
    img_arr:{
      mph:'',
      xct:{
        img1:'',
        img2: '',
        img3: ''
      }
    },
    name: '',
    mobile: '',
    housing: '',
    address: '',
    remark:'',
    submit_flag: false   //提交标识 
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.id!=undefined){
      this.data.id=options.id
      model.getCustomerInfo(options.id,(res)=>{
        var resdata=res.data.data;
        var data={
          name:resdata.name,
          mobile:resdata.mobile,
          area_address: resdata.province+'-'+resdata.city+'-'+resdata.area,
          province:resdata.province,
          city:resdata.city,
          area:resdata.area,
          housing:resdata.housing,
          address: resdata.address,
          remark: resdata.remark
        }
        this.setData(data);
      })
    }
  },

  // 选择地址
  changeArea: function () {
    this.setData({ select_address: true })
  },
  // 关闭地址选择
  onClose: function () {
    this.setData({
      select_address: false
    });
  },
  // 选择地址
  onSelectOk: function (e) {
    var detail = e.detail.values;
    this.data.province = detail[0]['name'];
    this.data.city = detail[1]['name'];
    this.data.area = detail[2]['name'];
    var area_address = detail[0]['name'] + '-' + detail[1]['name'] + '-' + detail[2]['name'];
    this.setData({ area_address: area_address })
    this.onClose();
  },
  // 提交订单
  formSubmit: function (e) {
    if (this.data.submit_flag) {   //防止重复提交
      return;
    }
    var value = e.detail.value;
    if (value.name.length <= 0) {
      wx.showToast({
        title: '客户姓名必填', icon: 'none'
      })
      return;
    }

    if (value.mobile.length <= 0) {
      wx.showToast({
        title: '客户手机号必填', icon: 'none'
      })
      return;
    }

    if (value.mobile.length < 11) {
      wx.showToast({ title: '客户手机号码长度有误！', icon: 'none' })
      return;
    }


    var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;// 判断手机号码的正则
    if (!myreg.test(value.mobile)) {
      wx.showToast({ title: '手机号码格式错误！', icon: 'none' })
      return;
    }

    
    if (value.area_address.length <= 0) {
      wx.showToast({
        title: '请选择地区', icon: 'none'
      })
      return;
    }
    if (value.housing.length <= 0) {
      wx.showToast({
        title: '小区名称必填', icon: 'none'
      })
      return;
    }
    if (value.address.length <= 0) {
      wx.showToast({
        title: '请填写详细地址', icon: 'none'
      })
      return;
    }

    if (this.data.img_arr.mph == '') {
      wx.showToast({
        title: "请添加门牌号图片", icon: 'none'
      })
      return;
    }

    for (var item in this.data.img_arr.xct ){
      if (this.data.img_arr.xct[item] == '') {
        wx.showToast({
          title: "请完善所有现场图片", icon: 'none'
        })
        return;
      }
    }
    
    var data = {
      province: this.data.province,
      city: this.data.city,
      area: this.data.area,
      address: value.address,
      mobile: value.mobile,
      name: value.name,
      housing:value.housing,
      remark:value.remark
    };
    data.id=this.data.id
    this.data.submit_flag = true;
    model.setCustomer(data, (res) => {   //先提交报备信息
      var statusCode = res.statusCode;
      var toast=res.data.msg;
      if (statusCode == 200) {
        this.upload(res.data.data.id,()=>{  //上传图片
          wx.showToast({
            title:toast, icon: 'success',mask:true
          });
          setTimeout(function () {
            wx.navigateTo({
              url: '/pages/customer/index',
            });
          }, 1000);
        })   
      } else {
        wx.showToast({
          title: toast, icon: 'none'
        });
      }
    })
  },
  // 上传图片方法
  upload:function(customer_id,callback){
    wx.showLoading({
      title: '上传中……',mask:true
    });
    var img_arr=this.data.img_arr;
    var data={customer_id:customer_id};
    var i=0;  //统计图片上传次数
    var img_len=0;
    for(var item in img_arr){
      if(typeof img_arr[item]=='string'){
        img_len=1
        data.filePath=img_arr[item];
        data.index=item
        model.setUpload(data,(res)=>{
          i++;
        })
      }
      if(typeof img_arr[item]=='object'){
        img_len+=Object.keys(img_arr[item]).length; 
        var items=img_arr[item];
        for(var item2 in items){
          data.filePath=items[item2];
          data.index=item+'.'+item2
          model.setUpload(data,(res)=>{
            i++;
            if(img_len==i){   //全部图片上传成功
              wx.hideLoading();
              callback&&callback()
            }
          })
        }
      }
    }
  },

  // // 提交上传信息
  // upload: function (customer_id,callback) {
  //   var that = this
  //   var img_arr = this.data.img_arr
  //   var img_len=Object.keys(img_arr).length; var i=0;  //统计图片上传次数
  //   for (var index in img_arr){
  //     wx.uploadFile({
  //       url: model.baseRestUrl + '/customer_img',
  //       filePath: img_arr[index]+'',
  //       name: 'file',
  //       header: { 'content-type': 'application/json', 'token': wx.getStorageSync('token') },
  //       formData: { img_type: index ,id:customer_id},
  //       success: function (res) {
  //         var data = JSON.parse(res.data)
  //         var statusCode = res.statusCode;
  //         if (statusCode == 401) {   //token 错误
  //           var token = new Token();
  //           token.getToken((res) => {
  //             that.upload(customer_id,callback);
  //           })
  //         }
  //         wx.hideLoading();
  //         if (statusCode != 200) {  //上传失败
  //           wx.showToast({
  //             title: data.msg, icon: 'none'
  //           })
  //           return;
  //         }
  //         i++;
  //         if(img_len==i) {   //如果图片全部上传完成，则提交数据
  //           console.log('提交数据');
  //           callback&&callback()
  //         } 
  //       },
  //       fail: function (res) {
  //         wx.showToast({
  //           title: '网络错误，请稍后重试~',
  //           icon: 'none'
  //         });
  //       }
  //     })
  //   }
  // },
  // // 上传图片
  uploadImg: function (e) {
    console.log(e)
    var img_type=e.currentTarget.dataset.type;
    var that = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            that.chooseWxImage('album', img_type)
          } else if (res.tapIndex == 1) {
            that.chooseWxImage('camera', img_type)
          }
        }
      }
    });
  },
  // 选择图片
  chooseWxImage: function (sourceType, img_type) {
    var that = this;
    var img_type_arr=img_type.split(".");
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'],
      sourceType: [sourceType],
      success: function (res) {
        var data = {};
        if(img_type_arr.length==2){  //上传多个图片
          that.data.img_arr[img_type_arr[0]][img_type_arr[1]] = res.tempFilePaths[0]; 
        }else{
          data[img_type] = res.tempFilePaths[0];
          that.data.img_arr[img_type] = data[img_type]; 
        } 
        that.setData({ img_arr: that.data.img_arr})    
      },
      fail: function (res) {
        console.log(res)
      }
    })
  }
})